import tkinter as tk
from tkinter import ttk
import tkinter.messagebox as messagebox
import  os,codecs
import requests,re
import zipfile
import winshell,shutil

version = "1.0.9"
pwd=os.getcwd()

class base_win(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('工具')
        self.geometry('330x420+290+150')
        self.wm_resizable(False, False)
        self.iconbitmap('icon\\index.ico')
        file = codecs.open("OpsTools_set.conf", 'r', 'utf-8', buffering=True)
        down_load_1 = file.read()
        self.base_url = re.findall(r'<BASE_URL>(.*?)</BASE_URL>', down_load_1, re.S)[0]
        self.down_load = re.findall(r'<DOWNLOAD_PATH>(.*?)</DOWNLOAD_PATH>', down_load_1, re.S)
        def save():
            self.password = str(self.passwd_1_value.get())
            self.user = str(self.user_1_value.get())

            if self.passwd_1_value.get() != "" and self.user_1_value.get() != "":
                try:
                    login = requests.get(self.base_url, auth=(self.user, self.password), verify=False)
                    login.encoding = 'gbk'
                    self.login = login.text
                    if "由于凭据无效" in self.login:
                        messagebox.showinfo('提示', '账号或密码错误！')

                    else:
                        self.USER.destroy()
                        self.user_1_value.destroy()
                        self.PASSWD.destroy()
                        self.passwd_1_value.destroy()
                        self.set_cancel.destroy()
                        self.set_save.destroy()
                        self.a.destroy()
                        self.b.destroy()
                        self.c.destroy()
                        self.d.destroy()
                        self.base()
                except:
                    messagebox.showinfo('提示', '账号或密码错误！')
            else:
                messagebox.showinfo('提示', '未输入账号或密码!')
            self.OpsTools_version_server = requests.get(self.base_url + "/OpsTools/OpsTools_version.txt",auth=(self.user, self.password), verify=False)
            self.OpsTools_version_server.encoding = 'gbk'
            self.OpsTools_version_server = self.OpsTools_version_server.text
            Client_Notice = requests.get(self.base_url + "/OpsTools/Notice.txt", auth=(self.user, self.password),verify=False)
            Client_Notice.encoding = 'gbk'
            self.Client_Notice = Client_Notice.text

            try:
                pwd = os.path.abspath(os.path.join(os.getcwd()) + "\\..")

                target = "%s\\OpsTools_%s\\OpsTools_%s.exe" % (pwd, version, version)
                s = os.path.basename(target)
                fname = os.path.splitext(s)[0]
                isexists = os.path.exists(
                    os.path.join(os.path.expanduser("~"), 'Desktop' + "\\" + "OpsTools_%s.lnk" % version))
                isexists_new = os.path.exists(os.path.join(os.path.expanduser("~"),
                                                           'Desktop' + "\\" + "OpsTools_%s.lnk" % self.OpsTools_version_server))
                if isexists or isexists_new:
                    pass
                else:
                    winshell.CreateShortcut(
                        Path=os.path.join(winshell.desktop(), fname + '.lnk'),
                        Target=target,
                        Arguments=target,
                        StartIn=os.getcwd(),
                        Icon=(target, 0))

            except:
                messagebox.showinfo('提示', '快捷方式创建失败!')

        def cancel():
            self.destroy()

        self.a = tk.Label(self, text="")
        self.a.grid(row=1, column=0, columnspan=1)
        self.b = tk.Label(self, text="")
        self.b.grid(row=2, column=0, columnspan=1)
        self.c = tk.Label(self, text="")
        self.c.grid(row=3, column=0, columnspan=1)
        self.d = tk.Label(self, text="")
        self.d.grid(row=4, column=0, columnspan=1)
        self.USER = tk.Label(self, text="账号:")
        self.USER.grid(row=5, column=1, columnspan=1, pady=10, padx=25)
        self.user = tk.StringVar(value="kevin")
        self.user_1_value = tk.Entry(self, textvariable=self.user, width=25)
        self.user_1_value.grid(row=5, column=2, columnspan=11, pady=2)
        self.PASSWD = tk.Label(self, text="密码:")
        self.PASSWD.grid(row=6, column=1, columnspan=1, pady=1, padx=25)
        self.passwd_1_value = tk.Entry(self, show="*", width=25)
        self.passwd_1_value.grid(row=6, column=2, columnspan=11, pady=2)

        self.set_cancel = tk.Button(self, text='退出', width=7, height=2, command=cancel)
        self.set_cancel.grid(row=66, column=0, columnspan=9, pady=50, padx=48)
        self.set_save = tk.Button(self, text='登录', width=7, height=2, command=save)
        self.set_save.grid(row=66, column=7, columnspan=11, pady=50, padx=15)

        def save_1(func):
            save()
        self.bind("<Return>",save_1)

    def title_1(self):
        list_server = requests.get(self.base_url+'/packages_list.txt', auth=(self.user, self.password), verify=False)
        list_server.encoding = 'gbk'
        list_server = list_server.text
        return list_server
    def go(self):
        self.change_0.destroy()
        self.type_0.destroy()
        self.Notice.destroy()
        self.up_1.destroy()
        self.flush_1.destroy()

        self.base()
    def base(self):
        Client_Notice = requests.get(self.base_url + "/OpsTools/Notice.txt", auth=(self.user, self.password), verify=False)
        Client_Notice.encoding = 'gbk'
        Client_Notice = Client_Notice.text
        self.OpsTools_version_server = requests.get(self.base_url + "/OpsTools/OpsTools_version.txt",
                                                    auth=(self.user, self.password), verify=False)
        self.OpsTools_version_server.encoding = 'gbk'
        self.OpsTools_version_server = self.OpsTools_version_server.text
        self.change_0 = tk.Label(self,text='操作:')
        self.change_0.grid(row=0,column=0,columnspan=2,pady=15)
        self.ty_0 = tk.StringVar()  # #创建变量，便于取值
        self.type_0 = ttk.Combobox(self, width=35, textvariable=self.ty_0, state='readonly')  # #创建下拉菜单
        self.type_0.grid(row=0, column=1, columnspan=14, pady=15)  # #将下拉菜单绑定到窗体


        all = self.title_1()
        version_title = re.findall(r'<title>(.*?)</title>', self.title_1(), re.S)
        self.type_0["value"] = version_title  # #给下拉菜单设定值
        self.type_0.current(0)  # #设定下拉菜单的默认值为第0个
        self.Notice = tk.Text(self, width=43, height=15)
        self.Notice.grid(row=2, column=0, columnspan=15, padx=12, pady=10)
        self.Notice.insert('end', Client_Notice + '\n')
        self.Notice.config(state='disabled')

        self.up_1 = tk.Button(self, text='更新', width=9, height=2, command=self.update_1)
        self.up_1.grid(row=180, column=1, columnspan=5, padx=1, pady=50)
        self.flush_1 = tk.Button(self, text='刷新', width=9, height=2, command=self.go)
        self.flush_1.grid(row=180, column=8, columnspan=9, padx=35, pady=50)
        def xFunc(event):
            self.value = re.compile(r'<title>%s</title>\r\n<type>(.*?)</type>\r\n<path>(.*?)</path>\r\n<start_exe>(.*?)</start_exe>' % self.type_0.get())
            self.value = self.value.findall(all)
            url = '%s/%s/version.txt' % (self.base_url, self.value[0][1])
            self.server_type = self.value[0][0]
            self.server_path = self.value[0][1]
            self.server_start = self.value[0][2]
            version_server = requests.get(url, auth=(self.user, self.password), verify=False)
            version_server.encoding = 'gbk'
            version_server = version_server.text
            self.run(version_server,self.server_type,self.server_path,self.server_start)
        self.type_0.bind("<<ComboboxSelected>>", xFunc)
    def update_1(self):
        if self.OpsTools_version_server != version and messagebox.askokcancel('提示','是否更新版本？\r\n当前版本:%s--->最新版本:%s'%(version,self.OpsTools_version_server)):
            download_OpsTools  = requests.get(self.base_url+'/OpsTools/OpsTools_%s.zip'%self.OpsTools_version_server,auth=(self.user, self.password), verify=False)
            with open("..\\OpsTools_%s.zip" %self.OpsTools_version_server, 'wb') as file:
                file.write(download_OpsTools.content)
                file.close()
            if messagebox.askokcancel('完成', '下载完成，是否运行?'):
                try:
                    pwd=os.path.abspath(os.path.join(os.getcwd())+"\\..")
                    target = "%s\\OpsTools_%s\\OpsTools_%s.exe" % (pwd,self.OpsTools_version_server,self.OpsTools_version_server)
                    s = os.path.basename(target)
                    fname = os.path.splitext(s)[0]
                    isexists = os.path.exists(
                        os.path.join(os.path.expanduser("~"), 'Desktop' + "\\" + "OpsTools_%s.lnk" % self.OpsTools_version_server))
                    if isexists:
                        pass
                    else:
                        winshell.CreateShortcut(
                            Path=os.path.join(winshell.desktop(), fname + '.lnk'),
                            Target=target,
                            Arguments=target,
                            StartIn=pwd + "\\OpsTools_%s" % self.OpsTools_version_server,
                            Icon=(target, 0))
                except:
                    messagebox.showinfo('提示', '快捷方式创建失败!')
                new_file = "..\\OpsTools_%s\\OpsTools_%s.exe" % ( self.OpsTools_version_server, self.OpsTools_version_server)
                zFile = zipfile.ZipFile("..\\OpsTools_%s.zip" % self.OpsTools_version_server, "r")
                for fileM in zFile.namelist():
                    zFile.extract(fileM, '..//')
                zFile.close()
                os.startfile(new_file)
                self.destroy()
                os.remove("..\\OpsTools_%s.zip" % self.OpsTools_version_server)
            else:
                exit()
        else:
            messagebox.showinfo('提示','当前版本:%s--->最新版本:%s'%(version,self.OpsTools_version_server))

    def run(self,ver,type,path,start):
        try:
            if not os.path.exists(self.down_load[0]):
                os.mkdir(self.down_load[0])
            if type == "zip":
                if not os.path.exists(self.down_load[0]+"//"+path+"_"+ver):
                    if messagebox.askokcancel('提示','是否下载%s_%s？'%(path,ver)):
                        url_exe = self.base_url+"/%s/%s_%s.zip" % (path, path, ver)
                        vers = requests.get(url_exe, auth=(self.user, self.password), verify=False)
                        with open(self.down_load[0]+"/%s_%s.zip" % (path, ver), 'wb') as file:
                            file.write(vers.content)
                            file.close()
                        if messagebox.askokcancel('完成','下载完成，是否运行?'):
                            new_file = self.down_load[0]+"\\%s_%s\\%s_%s.exe" % (path,ver,path,ver)
                            zFile = zipfile.ZipFile(self.down_load[0]+"/%s_%s.zip" %(path,ver), "r")
                            for fileM in zFile.namelist():
                                zFile.extract(fileM, self.down_load[0]+'//')
                            zFile.close()
                            os.startfile(new_file)
                            os.remove(self.down_load[0]+"//%s_%s.zip" %(path,ver))
                else:
                    if messagebox.askokcancel('提示','是否运行%s_%s?'%(path,ver)):
                        new_file = self.down_load[0]+"\\%s_%s\\%s_%s.exe" % (path, ver, path, ver)
                        try:
                            os.startfile(new_file)
                        except:
                            messagebox.showinfo('错误','启动失败！')
            else:
                if  not os.path.exists(self.down_load[0]+'\\'+start) and not os.path.exists(self.down_load[0]+'\\'+start[:-3]+"bat"):
                    if messagebox.askokcancel('提示', '是否下载%s?' % path):
                        if not os.path.exists(self.down_load[0]+"\\" + path):
                            os.mkdir(self.down_load[0]+"\\" + path)
                        url_exe = self.base_url+"/%s" % (start)
                        vers = requests.get(url_exe, auth=(self.user, self.password), verify=False)
                        with open(self.down_load[0]+"/%s" % start, 'wb') as file:
                            file.write(vers.content)
                            file.close()
                        if messagebox.askokcancel('完成', '下载完成，是否运行?'):
                            if type != "bat":
                                new_file = self.down_load[0]+"\\%s" % start
                            else:
                                os.rename(self.down_load[0]+"\\%s" % start,self.down_load[0]+"\\%s" % start[:-3]+"bat")
                                new_file = self.down_load[0]+"\\%s" % start[:-3]+"bat"
                            os.startfile(new_file)
                else:
                    if messagebox.askokcancel('提示', '是否运行%s.%s_%s?' % (path,type, ver)):
                        if type != "bat":
                            new_file = self.down_load[0]+"\\%s" % start
                        else:
                            new_file = self.down_load[0]+"\\%s" % start[:-3]+"bat"
                        try:
                            os.startfile(new_file)
                        except:
                            messagebox.showinfo('错误', '启动失败！')

        except:
            messagebox.showinfo('提示','更新失败！')



if __name__ == "__main__":
    base_win().mainloop()